<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
  >
    <el-form
      ref="formRef"
      label-width="100px"
      :model="state.formData"
      :rules="state.formRules"
    >
      <el-row>
        <el-col :span="16">
          <el-row>
            <el-col :span="12">
              <el-form-item label="员工姓名:" prop="userName">
                <el-input
                  v-model="state.formData.userName"
                  :maxlength="16"
                  :show-word-limit="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="员工编号:" prop="labor">
                <el-input
                  v-model="state.formData.labor"
                  :maxlength="16"
                  :show-word-limit="true"
                  type="text"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码:" prop="mobilePhone">
                <el-input
                  v-model="state.formData.mobilePhone"
                  :maxlength="16"
                  type="text"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户状态:" prop="status">
                <easy-dict-select
                  v-model:default-value="state.formData.status"
                  dict-code="1031"
                  show-all="N"
                  @change="handleUserStatusChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="员工岗位:" prop="jobName">
                <el-input
                  v-model="state.formData.jobName"
                  :maxlength="32"
                  :show-word-limit="true"
                >
                  <template #append>
                    <el-button icon="Search" @click="handleOpenJobPicker" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="员工性别:" prop="userSex">
                <easy-dict-select
                  v-model:default-value="state.formData.userSex"
                  dict-code="1001"
                  show-all="N"
                  @change="handleUserSexChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-form-item label="图片:" prop="certImg">
            <div
              style="width: 204px; height: 142.5px; border: 1px solid #dcdcdc"
            >
              <el-image
                fit="fill"
                :src="state.formData.certImg"
                style="cursor: pointer"
                @click="openPictureCropperDialog"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="所属部门:" prop="deptIds">
            <el-button
              icon="Search"
              style="margin-right: 10px"
              @click="handleOpenDeptSelector"
            />
            <el-tag
              v-for="(item, index) in state.deptList"
              :key="item"
              closable
              :disable-transitions="false"
              @close="handleCloseDept(index)"
            >
              {{ item.text }}
            </el-tag>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="主部门:" prop="mainDeptId">
            <el-select v-model="state.formData.mainDeptId" placeholder="请选择">
              <el-option
                v-for="item in state.deptList"
                :key="item.id"
                :label="item.text"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="部门领导:" prop="leader">
            <el-radio-group v-model="state.formData.leader">
              <el-radio label="否" value="0"></el-radio>
              <el-radio label="是" value="1"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="身份证号:" prop="certNo">
            <el-input v-model="state.formData.certNo" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="办公电话:" prop="telephone">
            <el-input v-model="state.formData.telephone" type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电子邮箱:" prop="email">
            <el-input v-model="state.formData.email" type="text" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="办公位置:" prop="location">
            <el-input
              v-model="state.formData.location"
              :maxlength="64"
              :show-word-limit="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位:" prop="positionName">
            <el-input
              v-model="state.formData.positionName"
              :maxlength="32"
              :show-word-limit="true"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系地址:" prop="address">
            <el-input
              v-model="state.formData.address"
              :maxlength="64"
              :show-word-limit="true"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="state.formData.remark"
              :maxlength="128"
              :rows="4"
              :show-word-limit="true"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button icon="circle-close" type="warning" @click="close">
        取消
      </el-button>
      <el-button
        :disabled="state.readonly"
        icon="circle-check"
        type="primary"
        @click="save"
      >
        确定
      </el-button>
    </template>
    <JobPicker
      ref="jobPickerRef"
      :multiple="false"
      title="选择岗位"
      width="60%"
      @change="handleJobSelect"
    />
    <DeptSelector
      ref="deptRef"
      :multiple="true"
      title="选择组织"
      width="40%"
      @change="handleDeptSelect"
    />
    <PictureCropper
      ref="pictureCropperRef"
      @confirm="handlePictureCropperConfirm"
    />
  </el-dialog>
</template>

<script setup name="StaffEdit">
import { useMessage } from "@/hooks/message";
import { addStaff, updateStaff, queryStaff } from "@/api/admin/org/staff/";
import { cloneObject } from "@/utils/common";
import {
  validIdCard,
  validMobilePhone,
  validPhone,
  validEmail
} from "@/utils/rules";
import EasyDictSelect from "@/components/dictSelect.vue";
import DeptSelector from "@/components/deptTreePicker.vue";
import JobPicker from "@/components/jobPicker.vue";
import PictureCropper from "@/components/pictureCropper.vue";
import defaultCertImg from "@/assets/empty_images/data_empty.png";

const props = defineProps({
  title: {
    type: String,
    default: "员工"
  },
  width: {
    type: String,
    default: "20%"
  },
  model: {
    type: Boolean,
    default: true
  }
});
const emits = defineEmits(["confirm"]);

const formRef = ref(null);
const deptRef = ref(null);
const jobPickerRef = ref(null);
const pictureCropperRef = ref(null);

const state = reactive({
  dialogTitle: props.title,
  readonly: false,
  operationAdd: false,
  deptList: [],
  formData: {
    id: "",
    userName: "",
    labor: "",
    jobId: "",
    mobilePhone: "",
    certNo: "",
    telephone: "",
    email: "",
    positionName: "",
    jobName: "",
    userSex: "",
    userSource: "0",
    mainDeptId: "",
    mainDeptName: "",
    location: "",
    address: "",
    remark: "",
    status: "",
    deptNames: [],
    deptIds: [],
    leader: "0",
    certImg: defaultCertImg
  },
  certImgChange: false,
  formRules: {
    userName: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" }
    ],
    status: [{ required: true, message: "用户状态不能为空", trigger: "blur" }],
    deptIds: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
    leader: [
      { required: true, message: "是否部门领导不能为空", trigger: "blur" }
    ],
    mainDeptId: [
      { required: true, message: "主部门不能为空", trigger: "blur" }
    ],
    userSex: [{ required: true, message: "员工性别不能为空", trigger: "blur" }],
    mobilePhone: [
      {
        validator: validMobilePhone,
        trigger: "change"
      }
    ],
    certNo: [
      {
        validator: validIdCard,
        trigger: "change"
      }
    ],
    telephone: [
      {
        validator: validPhone,
        trigger: "change"
      }
    ],
    email: [
      {
        validator: validEmail,
        trigger: "change"
      }
    ]
  },
  dialogVisible: false
});

const show = (row, readonly) => {
  if (readonly) {
    state.dialogTitle = `${props.title}详情`;
    state.readonly = readonly;
  } else {
    state.readonly = false;
  }
  if (row && row.id) {
    state.dialogTitle = `编辑${props.title}`;
    state.formData.id = row.id;
    fetchData();
  } else {
    state.operationAdd = true;
    state.dialogTitle = `新增${props.title}`;
  }
  state.dialogVisible = true;
};

const close = () => {
  state.readonly = false;
  state.operationAdd = false;
  state.dialogTitle = props.title;
  state.deptList = [];
  state.formData = {
    id: "",
    userName: "",
    labor: "",
    jobId: "",
    mobilePhone: "",
    certNo: "",
    telephone: "",
    email: "",
    positionName: "",
    jobName: "",
    userSex: "",
    userSource: "0",
    mainDeptId: "",
    location: "",
    address: "",
    remark: "",
    status: "",
    deptNames: [],
    deptIds: [],
    leader: "0",
    certImg: defaultCertImg
  };
  state.certImgChange = false;
  state.dialogVisible = false;
};

const save = () => {
  const loadInstance = ElLoading.service();
  formRef.value.validate(async (valid, callback) => {
    if (valid) {
      state.readonly = true;
      let data;
      if (state.operationAdd) {
        data = await addStaff(state.formData);
      } else {
        if (!state.certImgChange) {
          state.formData.certImg = null;
        }
        data = await updateStaff(state.formData);
      }
      if (data.code && data.code === 200) {
        useMessage().success(data.msg);
        emits("confirm", {});
        close();
      } else {
        state.readonly = false;
        usesMessage().error(data.msg);
      }
    }
  });
  loadInstance.close();
};

const openPictureCropperDialog = () => {
  pictureCropperRef.value.show();
};

const fetchData = async () => {
  const res = await queryStaff(state.formData.id);
  if (res.code === 200) {
    cloneObject(state.formData, res.data);
    if (!state.formData.certImg) {
      state.formData.certImg = defaultCertImg;
    }
    if (state.formData.deptIds) {
      const deptList = [];
      state.formData.deptIds.forEach((item, index) => {
        const deptItem = {};
        deptItem.id = item;
        deptItem.text = state.formData.deptNames[index];
        deptList.push(deptItem);
      });
      state.deptList = deptList;
      state.formData.mainDeptId = res.data.mainDeptId;
    }
  }
};

const handleUserSexChange = val => {
  state.formData.userSex = val;
};

const handleUserStatusChange = val => {
  state.formData.status = val;
};

const handleOpenDeptSelector = () => {
  deptRef.value.show();
};

const handleOpenJobPicker = () => {
  jobPickerRef.value.show();
};

const handleJobSelect = rows => {
  if (rows && rows.length > 0) {
    state.formData.jobId = rows[0].id;
    state.formData.jobName = rows[0].jobName;
  }
};

const handleDeptSelect = rows => {
  state.deptList = rows;
  handleInitDepts();
};

const handleInitDepts = () => {
  state.formData.mainDeptId = "";
  state.formData.mainDeptName = "";
  state.formData.deptIds = state.deptList.map(function (item) {
    return item.id;
  });
  state.formData.deptNames = state.deptList.map(function (item) {
    return item.text;
  });
};

const handleCloseDept = index => {
  state.deptList.splice(index, 1);
  handleInitDepts();
  console.log("handleCloseDept", state.deptList);
};

const handlePictureCropperConfirm = async value => {
  state.certImgChange = true;
  state.formData.certImg = value;
};

defineExpose({
  show,
  close,
  save
});
</script>
<style lang="scss" scoped>
.el-input__inner {
  width: 140px;
}
</style>
